package com.sora.pipeline.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sora.pipeline.common.api.ApiResponse;
import com.sora.pipeline.domain.Line;
import com.sora.pipeline.domain.Milestone;
import com.sora.pipeline.domain.dto.*;
import com.sora.pipeline.service.LineService;
import com.sora.pipeline.service.MilestoneService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 线路管理控制器
 * 
 * @author system
 * @since 2025-01-20
 */
@RestController
@RequestMapping("/api/lines")
@Validated
public class LineController {

    @Autowired
    private LineService lineService;
    
    @Autowired
    private MilestoneService milestoneService;

    /**
     * 1. 获取线路列表
     * 分页获取线路列表，支持搜索和筛选
     */
    @GetMapping
    public ApiResponse<IPage<Line>> getLines(
            @RequestParam int pageNum,
            @RequestParam int pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String region) {
        
        LambdaQueryWrapper<Line> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Line::getDeleted, false);
        
        // 搜索条件
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                .like(Line::getLineCode, keyword)
                .or()
                .like(Line::getLineName, keyword)
            );
        }
        
        // 状态筛选
        if (StringUtils.hasText(status)) {
            queryWrapper.eq(Line::getStatus, status);
        }
        
        // 区域筛选
        if (StringUtils.hasText(region)) {
            queryWrapper.eq(Line::getRegion, region);
        }
        
        queryWrapper.orderByDesc(Line::getCreatedAt);
        
        IPage<Line> page = lineService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return ApiResponse.success(page);
    }

    /**
     * 2. 获取线路详情
     * 根据ID获取线路详细信息
     */
    @GetMapping("/{id}")
    public ApiResponse<Line> getLine(@PathVariable Long id) {
        Line line = lineService.getById(id);
        if (line == null || line.getDeleted()) {
            return ApiResponse.failure(404, "线路不存在");
        }
        return ApiResponse.success(line);
    }

    /**
     * 3. 创建线路
     * 创建新的线路
     */
    @PostMapping
    public ApiResponse<Line> createLine(@Valid @RequestBody LineRequest request) {
        // 检查线路编号是否已存在
        LambdaQueryWrapper<Line> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Line::getLineCode, request.getLineCode())
                   .eq(Line::getDeleted, false);
        if (lineService.count(queryWrapper) > 0) {
            return ApiResponse.failure(400, "线路编号已存在");
        }
        
        Line line = new Line();
        BeanUtils.copyProperties(request, line);
        line.setLengthKm(request.getLength());
        line.setStatus(StringUtils.hasText(request.getStatus()) ? request.getStatus() : "normal");
        line.setCreatedAt(LocalDateTime.now());
        line.setUpdatedAt(LocalDateTime.now());
        line.setDeleted(false);
        
        lineService.save(line);
        return ApiResponse.success(line);
    }

    /**
     * 4. 更新线路
     * 更新线路信息
     */
    @PutMapping("/{id}")
    public ApiResponse<Line> updateLine(@PathVariable Long id, @Valid @RequestBody LineRequest request) {
        Line line = lineService.getById(id);
        if (line == null || line.getDeleted()) {
            return ApiResponse.failure(404, "线路不存在");
        }
        
        // 检查线路编号是否已被其他线路使用
        LambdaQueryWrapper<Line> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Line::getLineCode, request.getLineCode())
                   .ne(Line::getId, id)
                   .eq(Line::getDeleted, false);
        if (lineService.count(queryWrapper) > 0) {
            return ApiResponse.failure(400, "线路编号已被其他线路使用");
        }
        
        BeanUtils.copyProperties(request, line);
        line.setLengthKm(request.getLength());
        line.setUpdatedAt(LocalDateTime.now());
        
        lineService.updateById(line);
        return ApiResponse.success(line);
    }

    /**
     * 5. 删除线路
     * 删除指定线路
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteLine(@PathVariable Long id) {
        Line line = lineService.getById(id);
        if (line == null || line.getDeleted()) {
            return ApiResponse.failure(404, "线路不存在");
        }
        
        // 检查是否有关联的巡检任务或缺陷记录
        // TODO: 这里需要检查关联表，暂时先软删除
        line.setDeleted(true);
        line.setUpdatedAt(LocalDateTime.now());
        lineService.updateById(line);
        
        return ApiResponse.success(null);
    }

    /**
     * 6. 批量删除线路
     * 批量删除线路
     */
    @PostMapping("/batch-delete")
    public ApiResponse<Void> batchDeleteLines(@Valid @RequestBody BatchDeleteRequest request) {
        List<Line> lines = lineService.listByIds(request.getIds());
        if (lines.isEmpty()) {
            return ApiResponse.failure(404, "没有找到要删除的线路");
        }
        
        // 批量软删除
        lines.forEach(line -> {
            line.setDeleted(true);
            line.setUpdatedAt(LocalDateTime.now());
        });
        lineService.updateBatchById(lines);
        
        return ApiResponse.success(null);
    }

    /**
     * 7. 获取线路统计信息
     * 获取线路统计数据
     */
    @GetMapping("/statistics")
    public ApiResponse<Map<String, Object>> getLineStatistics() {
        LambdaQueryWrapper<Line> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Line::getDeleted, false);
        
        long totalLines = lineService.count(queryWrapper);
        
        // 按状态统计
        queryWrapper.clear();
        queryWrapper.eq(Line::getDeleted, false).eq(Line::getStatus, "normal");
        long normalCount = lineService.count(queryWrapper);
        
        queryWrapper.clear();
        queryWrapper.eq(Line::getDeleted, false).eq(Line::getStatus, "maintenance");
        long maintenanceCount = lineService.count(queryWrapper);
        
        queryWrapper.clear();
        queryWrapper.eq(Line::getDeleted, false).eq(Line::getStatus, "disabled");
        long disabledCount = lineService.count(queryWrapper);
        
        // 计算总里程
        queryWrapper.clear();
        queryWrapper.eq(Line::getDeleted, false);
        List<Line> allLines = lineService.list(queryWrapper);
        BigDecimal totalLength = allLines.stream()
            .map(Line::getLengthKm)
            .filter(km -> km != null)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        Map<String, Object> statistics = Map.of(
            "totalLines", totalLines,
            "totalLength", totalLength,
            "normalCount", normalCount,
            "maintenanceCount", maintenanceCount,
            "disabledCount", disabledCount
        );
        
        return ApiResponse.success(statistics);
    }

    /**
     * 8. 获取里程桩列表
     * 获取指定线路的里程桩列表
     */
    @GetMapping("/{lineId}/milestones")
    public ApiResponse<List<Milestone>> getMilestones(@PathVariable Long lineId) {
        // 检查线路是否存在
        Line line = lineService.getById(lineId);
        if (line == null || line.getDeleted()) {
            return ApiResponse.failure(404, "线路不存在");
        }
        
        LambdaQueryWrapper<Milestone> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Milestone::getLineId, lineId)
                   .eq(Milestone::getDeleted, false)
                   .orderByAsc(Milestone::getKm);
        
        List<Milestone> milestones = milestoneService.list(queryWrapper);
        return ApiResponse.success(milestones);
    }

    /**
     * 9. 创建里程桩
     * 为指定线路创建里程桩
     */
    @PostMapping("/{lineId}/milestones")
    public ApiResponse<Milestone> createMilestone(@PathVariable Long lineId, @Valid @RequestBody MilestoneRequest request) {
        // 检查线路是否存在
        Line line = lineService.getById(lineId);
        if (line == null || line.getDeleted()) {
            return ApiResponse.failure(404, "线路不存在");
        }
        
        // 检查里程桩编号是否已存在
        LambdaQueryWrapper<Milestone> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Milestone::getLineId, lineId)
                   .eq(Milestone::getCode, request.getCode())
                   .eq(Milestone::getDeleted, false);
        if (milestoneService.count(queryWrapper) > 0) {
            return ApiResponse.failure(400, "里程桩编号已存在");
        }
        
        Milestone milestone = new Milestone();
        BeanUtils.copyProperties(request, milestone);
        milestone.setLineId(lineId);
        milestone.setStatus(StringUtils.hasText(request.getStatus()) ? request.getStatus() : "normal");
        milestone.setCreatedAt(LocalDateTime.now());
        milestone.setUpdatedAt(LocalDateTime.now());
        milestone.setDeleted(false);
        
        milestoneService.save(milestone);
        return ApiResponse.success(milestone);
    }

    /**
     * 10. 批量创建里程桩
     * 批量创建里程桩
     */
    @PostMapping("/{lineId}/milestones/batch")
    public ApiResponse<List<Milestone>> batchCreateMilestones(@PathVariable Long lineId, @Valid @RequestBody BatchMilestoneRequest request) {
        // 检查线路是否存在
        Line line = lineService.getById(lineId);
        if (line == null || line.getDeleted()) {
            return ApiResponse.failure(404, "线路不存在");
        }
        
        // 验证参数
        if (request.getStartKm().compareTo(request.getEndKm()) >= 0) {
            return ApiResponse.failure(400, "起始公里数必须小于结束公里数");
        }
        
        String prefix = StringUtils.hasText(request.getPrefix()) ? request.getPrefix() : "K";
        List<Milestone> milestones = new ArrayList<>();
        
        BigDecimal currentKm = request.getStartKm();
        int counter = 1;
        
        while (currentKm.compareTo(request.getEndKm()) <= 0) {
            Milestone milestone = new Milestone();
            milestone.setLineId(lineId);
            milestone.setCode(prefix + currentKm);
            milestone.setKm(currentKm);
            milestone.setLng(BigDecimal.ZERO); // 默认值，实际使用时需要设置
            milestone.setLat(BigDecimal.ZERO); // 默认值，实际使用时需要设置
            milestone.setStatus("normal");
            milestone.setCreatedAt(LocalDateTime.now());
            milestone.setUpdatedAt(LocalDateTime.now());
            milestone.setDeleted(false);
            
            milestones.add(milestone);
            currentKm = currentKm.add(request.getInterval());
            counter++;
            
            // 防止无限循环
            if (counter > 1000) {
                break;
            }
        }
        
        milestoneService.saveBatch(milestones);
        return ApiResponse.success(milestones);
    }
}
